/*
 * @lc app=leetcode.cn id=501 lang=cpp
 *
 * [501] 二叉搜索树中的众数
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    vector<int> res;
    int count = 0;
    int maxcount = 0;
    TreeNode *pre = NULL;
    vector<int> findMode(TreeNode *root)
    {
        //寻找二叉搜索树的众数 该二叉搜索树可以有重复值 可以有多个众数
        if (root == NULL)
        {
            return res;
        }
        //第一次遍历 求maxcount
        traval(root);
        //第二次加入res
        pre = NULL;
        traval2(root);
        return res;
    }
    void traval(TreeNode *node)
    {
        //中序遍历有序 两个节点 一个前置节点
        if (node == NULL)
        {
            return;
        }
        traval(node->left);
        if (pre == NULL)
        {
            //第一个节点
            count = 1;
        }
        else if (node->val == pre->val)
        {
            count++;
        }
        else
        {
            count = 1;
        }
        maxcount = max(maxcount, count);
        pre = node;
        traval(node->right);
    }
    void traval2(TreeNode *node)
    {
        //根据maxcount加入数组
        if (node == NULL)
        {
            return;
        }
        traval2(node->left);
        if (pre == NULL)
        {
            //第一个节点
            count = 1;
        }
        else if (node->val == pre->val)
        {
            count++;
        }
        else
        {
            count = 1;
        }
        if (count == maxcount)
        {
            res.push_back(node->val);
        }
        pre = node;
        traval2(node->right);
    }
};
// @lc code=end
